package com.ytjj.qmyx.users.service.impl;

import com.ytjj.qmyx.users.dao.UsersInfoDao;
import com.ytjj.qmyx.users.mapper.UsersBalanceRecordMapper;
import com.ytjj.qmyx.users.model.DynamicIncomeDto;
import com.ytjj.qmyx.users.model.UserBalanceDto;
import com.ytjj.qmyx.users.model.UsersBalanceRecord;
import com.ytjj.qmyx.users.model.UsersBalanceRecordExample;
import com.ytjj.qmyx.users.service.UserBalanceService;
import com.ytjj.qmyx.users.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 *
 *  *
 **/
@Service
@Slf4j
public class UserBalanceServiceImpl implements UserBalanceService {

    @Resource
    private UsersInfoDao usersInfoDao;
    @Resource
    private UsersBalanceRecordMapper usersBalanceRecordMapper;

    @Override
    public BigDecimal getMoney(Integer userId) {
        return usersInfoDao.findUserMoney(userId);
    }

    @Transactional
    @Override
    public void update(UserBalanceDto userBalanceDto) {
        log.info("===update balance==={}", userBalanceDto);
        if(StringUtils.isNotEmpty(userBalanceDto.getCode())) {
            boolean exist = usersInfoDao.countByCodeAndType(userBalanceDto.getUserId(), userBalanceDto.getCode(),userBalanceDto.getType());
            if(exist){
                return;
            }
        }
        BigDecimal totalMoney = usersInfoDao.findUserTotalMoney(userBalanceDto.getUserId());
        UsersBalanceRecord usersBalanceRecord = new UsersBalanceRecord();
        usersBalanceRecord.setUserId(userBalanceDto.getUserId());
        usersBalanceRecord.setOriginalBalance(totalMoney);
        usersBalanceRecord.setNewBalance(userBalanceDto.getType().equals("ADD") ? totalMoney.add(userBalanceDto.getUpdateMoney()) : totalMoney.subtract(userBalanceDto.getUpdateMoney()));
        usersBalanceRecord.setType(userBalanceDto.getType());
        usersBalanceRecord.setBalance(userBalanceDto.getUpdateMoney());
        usersBalanceRecord.setSource(userBalanceDto.getSource());
        usersBalanceRecord.setCode(userBalanceDto.getCode());
        BigDecimal money = null;
        BigDecimal brokerageNum = null;
        if(userBalanceDto.getAmountType().equals(2)){
            brokerageNum = usersInfoDao.findUserBrokerageNum(userBalanceDto.getUserId());
            if (null == brokerageNum) {
                brokerageNum = BigDecimal.ZERO;
            }
            brokerageNum = userBalanceDto.getType().equals("ADD") ? brokerageNum.add(userBalanceDto.getUpdateMoney()) : brokerageNum.subtract(userBalanceDto.getUpdateMoney());
            if (brokerageNum.compareTo(BigDecimal.ZERO) < 0) {
                brokerageNum = BigDecimal.ZERO;
            }
        }else{
            money = usersInfoDao.findUserMoney(userBalanceDto.getUserId());
            money = userBalanceDto.getType().equals("ADD") ? money.add(userBalanceDto.getUpdateMoney()) : money.subtract(userBalanceDto.getUpdateMoney());

            //现在是设置佣金的时候，相应的余额会递增，所以在余额抵扣的时候也需要相应的减去
            brokerageNum = usersInfoDao.findUserBrokerageNum(userBalanceDto.getUserId());
            brokerageNum = userBalanceDto.getType().equals("ADD") ? brokerageNum.add(userBalanceDto.getUpdateMoney()) : brokerageNum.subtract(userBalanceDto.getUpdateMoney());
            if (brokerageNum.compareTo(BigDecimal.ZERO) < 0) {
                brokerageNum = BigDecimal.ZERO;
            }
        }
        if ("SUB".equals(userBalanceDto.getType())) {
            usersInfoDao.updateMoney(userBalanceDto.getUserId(), totalMoney,money,brokerageNum);
        }else {
            usersInfoDao.updateMoney(userBalanceDto.getUserId(), usersBalanceRecord.getNewBalance(), money,brokerageNum);
        }
        usersInfoDao.save(usersBalanceRecord);
        log.info("===update balance===处理完毕");
    }

    /**
     * 查询我的收益
     * @param userId
     * @param sources
     * @return
     */
    @Override
    public List<UsersBalanceRecord> queryMyIncomeList(Integer userId, List<String> sources) {
        UsersBalanceRecordExample example = new UsersBalanceRecordExample();
        example.createCriteria().andUserIdEqualTo(userId).andSourceIn(sources).andTypeEqualTo("ADD");
        List<UsersBalanceRecord> records = usersBalanceRecordMapper.selectByExample(example);
        return records;
    }

    @Override
    public List<UsersBalanceRecord> queryMyIncomeListByTimeDimension(Integer userId, List<String> sources, Integer type) {
        UsersBalanceRecordExample example = new UsersBalanceRecordExample();
        UsersBalanceRecordExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId).andSourceIn(sources).andTypeEqualTo("ADD");
        if (1 == type) {
            Map<String, Object> result = DateUtils.curDay();
            Date startTime = (Date) result.get("dayStart");
            Date endTime = (Date) result.get("dayEnd");
            criteria.andCreateTimeBetween(startTime, endTime);
        }else if (2 == type) {
            Date mondayTime = DateUtils.getTimesWeekmorning();
            criteria.andCreateTimeBetween(mondayTime, new Date());
        }
        List<UsersBalanceRecord> records = usersBalanceRecordMapper.selectByExample(example);
        return records;
    }

    public static void main(String[] args) {
        LocalDate ld = LocalDate.now(ZoneId.systemDefault());
        LocalDateTime localDateTime = ld.atStartOfDay();
        Date startTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        LocalDateTime ldt_end = LocalDateTime.now(ZoneId.systemDefault());
        Date endTime = Date.from(ldt_end.atZone(ZoneId.systemDefault()).toInstant());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(sdf.format(startTime));
        System.out.println(sdf.format(endTime));


        ld.plusWeeks(-1);
        System.out.println(sdf.format(ld));
    }

    /**
     * 账户流水记录表
     * @param userId
     * @param balance
     * @param type
     * @param source
     * @param amountType
     * @return
     */
    @Override
    public BigDecimal recordBalance(Integer userId, BigDecimal balance, String type, String source, Integer amountType) {
        BigDecimal totalMoney = usersInfoDao.findUserTotalMoney(userId);
        UsersBalanceRecord usersBalanceRecord = new UsersBalanceRecord();
        usersBalanceRecord.setUserId(userId);
        usersBalanceRecord.setOriginalBalance(totalMoney);
        usersBalanceRecord.setNewBalance(type.equals("ADD") ? totalMoney.add(balance) : totalMoney.subtract(balance));
        usersBalanceRecord.setType(type);
        usersBalanceRecord.setBalance(balance);
        usersBalanceRecord.setSource(source);
        usersBalanceRecord.setCreateTime(new Date());
        usersInfoDao.save(usersBalanceRecord);

        BigDecimal money = null;
        BigDecimal brokerageNum = null;
        if(amountType.equals(2)){
            brokerageNum = usersInfoDao.findUserBrokerageNum(userId);
            if (null == brokerageNum) {
                brokerageNum = BigDecimal.ZERO;
            }
            brokerageNum = type.equals("ADD") ? brokerageNum.add(balance) : brokerageNum.subtract(balance);
            if (brokerageNum.compareTo(BigDecimal.ZERO) < 0) {
                brokerageNum = BigDecimal.ZERO;
            }
        }else{
            money = usersInfoDao.findUserMoney(userId);
            money = type.equals("ADD") ? money.add(balance) : money.subtract(balance);

            //现在是设置佣金的时候，相应的余额会递增，所以在余额抵扣的时候也需要相应的减去
            brokerageNum = usersInfoDao.findUserBrokerageNum(userId);
            brokerageNum = type.equals("ADD") ? brokerageNum.add(balance) : brokerageNum.subtract(balance);
            if (brokerageNum.compareTo(BigDecimal.ZERO) < 0) {
                brokerageNum = BigDecimal.ZERO;
            }
        }
        if ("SUB".equals(type)) {
            usersInfoDao.updateMoney(userId, totalMoney, balance, brokerageNum);
        }else {
            usersInfoDao.updateMoney(userId, usersBalanceRecord.getNewBalance(), money,brokerageNum);
        }
        return usersBalanceRecord.getNewBalance();
    }

    @Override
    public List queryUsersIncomeItemByUserIdAndTypeAndSource(Integer userId, String type, String source, Integer timeType) {
        List<DynamicIncomeDto> list = new ArrayList<>();
        if (1 == timeType) {
            list = usersInfoDao.queryUsersIncomeItemByUserIdAndTypeAndSource(userId, type, source);
        }else if (2 == timeType) {

        }
        return list;
    }
}
